<template>
  <div class="login">
    <div class="login_bg">
      <!--      <img class="logo" src="../../assets/icon_logo.png">-->
      <div class="logo">{{ loanProductName }}</div>
    </div>
    <div class="login_form">
      <p class="title">{{ $t('login') }}</p>
      <div class="form_item">
        <img class="icon" src="../../assets/icon_mobile.png">
        <input v-model="loginForm.phone" maxlength="10"  :placeholder="$t('hint_input_mobile_number')"/>
      </div>
      <div class="form_item">
        <img class="icon" src="../../assets/icon_shield.png">
        <input v-model="loginForm.smsCode" :placeholder="$t('hint_input_identifying_code')"/>
        <van-button :disabled="sendCodeDisabled" @click="sendCode" style="float: right" round :type="buttonType"
                    size="small">
          <span v-if="buttonType ==='default'" style="padding: 0 20px">{{ codeNum }}s</span>
          <span v-else>{{ codeText }}</span>
        </van-button>
      </div>
    </div>
    <div class="apply_now">
      <div style="display: flex;justify-content: center">
        <van-checkbox v-model="checkedServe" @change="checkChange" icon-size="16px" shape="square"></van-checkbox>
        <span class="agreement">
            <span>{{ $t('agreement') }}</span>
          <a :href="privacyHref" class="active">{{ $t('server') }}</a>
         </span>
      </div>
      <van-button class="confirm" :loading="loginBtnLoading" type="primary" @click="onLogin">{{
          $t('login')
        }}
      </van-button>
      <!--      <button disabled class="confirm" @click="onLogin">{{ $t('login') }}</button>-->
    </div>
  </div>
</template>

<script>
import {ref, reactive, onMounted, computed} from 'vue'
import {useI18n} from 'vue-i18n'
import {apiSendCode, apiOnLogin} from "@/api/login";
import {buryingPoint, uploadDeviceInfo} from '@/api/home'
import {
  Toast
} from "vant";
import router from "@/router";
import {debounce} from '@/utils/tool'
import {useStore} from "vuex";
import MobileDetect from "mobile-detect";

export default {
  setup() {
    const {tm} = useI18n()
    const store = useStore()
    let checkedServe = ref(true)
    let codeNum = ref(60)
    let buttonType = ref('primary')
    let codeText = ref(tm('send_code'))
    const timer = ref(null)
    const loanProductName = localStorage.getItem('productName')
    const channel = localStorage.getItem('channel')
    const privacyHref = computed(() => {
      const url = process.env.VUE_APP_AUTH
      return `${url}/${loanProductName}/register.html`
    })
    const sendCodeDisabled = ref(false)
    const loginBtnLoading = ref(false)
    const loginForm = reactive({
      phone: '',
      smsCode: '',
      osType: 'h5'
    })
    onMounted(() => {
      if (localStorage.getItem('isUserServe') === 'true') {
        checkedServe.value = true
      }
    })
    // 校验登录表单
    const verificationForm = () => {
      let message = ''
      const {phone, smsCode} = loginForm
      if (!phone) message = tm('hint_input_mobile_number')
      if (!smsCode) message = tm('hint_input_identifying_code')
      if (phone.length < 9) message = tm('format_phone_invalid')
      if (message) {
        Toast({
          message: message
        })
        return false
      } else {
        return true
      }
    }
    //发送验证码
    const sendCode = async () => {
      if (buttonType.value === 'default') return
      if (!loginForm.phone) {
        Toast({
          message: tm('hint_input_mobile_number')
        })
        return
      }
      if (loginForm.phone.length < 9) {
        Toast({
          message: tm('format_phone_invalid')
        })
        return
      }
      sendCodeDisabled.value = true
      const res = await apiSendCode({
        channel,
        smsType: '1',
        phone: loginForm.phone,
        loanProductName: loanProductName
      })
      if (res.code === 1) {
        sendCodeDisabled.value = false
        buttonType.value = 'default'
        timer.value = setInterval(() => {
          codeNum.value--
          if (codeNum.value === 0) {
            clearInterval(timer.value)
            codeNum.value = 60
            buttonType.value = 'primary'
          }
        }, 1000)
      } else {
        sendCodeDisabled.value = false
      }
    }
    //注册uv
    const uvBuryingPoint = async () => {
      await buryingPoint({
        type: 2,
        productName: loanProductName,
        channelCode: channel
      })
    }
    // 登录处理
    const onLogin = async () => {
      if (!checkedServe.value) return Toast({message: tm('hint_check_agreement')})
      if (verificationForm()) {
        loginBtnLoading.value = true
        // 设备系统
        const u = navigator.userAgent
        const osType = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 ? 'android' : 'ios';
        const params = {
          channel,
          ...loginForm,
          osType,
          smsType: '1',
          loanProductName: loanProductName
        }
        const res = await apiOnLogin(params)
        if (res.code === 1 || res.code === 10) {
          loginBtnLoading.value = false
          Toast({
            message: tm('login_success')
          })
          localStorage.setItem('isUserServe', 'true')
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('userId', res.data.userId)
          localStorage.setItem('phone', loginForm.phone)
          // 埋点uv
          uvBuryingPoint()
          // 上传设备信息
          saveDeviceInfo()
          router.push('/home/index')
        } else {
          loginBtnLoading.value = false
        }
      }
    }
    const saveDeviceInfo = async () => {
      const md = new MobileDetect(navigator.userAgent)
      await uploadDeviceInfo({
        is_simulator: 1,
        deviceInfo: md.phone() || '',
        osType: md.os() || '',
        mobileModel: md.mobile()
      })
    }
    // 清除loading
    store.dispatch('changeLoading', false)
    const checkChange = (val) => {
      checkedServe.value = val
    }
    return {
      checkedServe,
      loanProductName,
      onLogin,
      sendCode,
      loginForm,
      codeNum,
      buttonType,
      codeText,
      checkChange,
      privacyHref,
      sendCodeDisabled,
      loginBtnLoading
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100vh;
  background-color: #FFFFFF;
}

.login_bg {
  background-image: url("../../assets/ic_login_head_bg.png");
  height: 220px;
  background-size: 100% 100%;
  position: relative;

  .logo {
    position: absolute;
    color: #FFFFFF;
    font-size: 22px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.login_form {
  .title {
    font-size: 16px;
    color: #FF5551;
    padding: 0 30px;
  }

  .form_item {
    display: flex;
    padding: 0 30px 5px 30px;
    height: 35px;
    position: relative;
    align-items: center;
    margin-bottom: 15px;

    .icon {
      height: 20px;
      width: 16px;
      margin-right: 10px;
    }

    input {
      border: 0;
      font-size: 16px;
      width: 100%;
      flex: 1;
      padding-right: 15px;
    }
  }

  .form_item::after {
    content: "";
    width: 85%;
    position: absolute;
    text-align: center;
    bottom: 0;
    border-bottom: solid 1px #E5E5E5;
  }
}

.apply_now {
  margin-top: 60px;
  text-align: center;

  .agreement {
    font-family: PingFang SC;
    font-weight: 600;
    font-size: 12px;
    color: #7B7B7B;
    margin-left: 10px;

    .active {
      color: #FF6A42;
    }
  }

  .confirm {
    margin-top: 25px;
    margin-bottom: 50px;
    height: 38px;
    width: 70%;
    color: #ffffff;
    border: none;
    font-size: 18px;
    background: linear-gradient(-45deg, #FF5252, #FF8C3C);
    box-shadow: 0px 4px 10px 0px rgba(255, 92, 78, 0.52);
    border-radius: 29px;
  }
}
</style>
